import { getData } from '~/server/plugins/getData'
import { defineEventHandler } from 'h3'
import { replaceImageDomains } from '~/utils/configHelper'

export default defineEventHandler(async (event) => {
  try {
    // 获取路径参数
    const category = event.context.params?.category ? decodeURIComponent(event.context.params.category) : ''
    const subCategory = event.context.params?.subCategory ? decodeURIComponent(event.context.params.subCategory) : ''
    const appName = event.context.params?.appName ? decodeURIComponent(event.context.params.appName) : ''
    
    // 验证参数
    if (!category || !subCategory || !appName) {
      return {
        success: false,
        message: '一级分类、二级分类和应用名称参数不能为空',
        data: null,
        error: 'MISSING_PARAMETERS'
      }
    }
    
    // 使用插件提供的数据
    const { getCurrentRequestData, getDataSourceData } = getData()
    
    // 获取当前域名的数据
    const currentData = getCurrentRequestData(event)
    
    if (!currentData) {
      return {
        success: false,
        message: '无法获取当前域名的数据',
        data: null,
        error: 'NO_DATA_AVAILABLE'
      }
    }
    
    const categoryData = currentData.data
    
    // 检查一级分类是否存在
    if (!categoryData.mainCategories.includes(category)) {
      return {
        success: false,
        message: `一级分类 "${category}" 不存在`,
        data: null,
        error: 'INVALID_MAIN_CATEGORY',
        availableMainCategories: categoryData.mainCategories
      }
    }

    // 检查二级分类是否存在
    const subCategories = categoryData.subCategories[category] || []
    if (!subCategories.includes(subCategory)) {
      return {
        success: false,
        message: `二级分类 "${subCategory}" 不存在`,
        data: null,
        error: 'INVALID_SUB_CATEGORY',
        availableSubCategories: subCategories
      }
    }
    
    // 获取指定分类下的应用数据
    const categoryDataForMain = categoryData.categoryData[category] || {}
    const apps = categoryDataForMain[subCategory] || []
    
    // 查找指定应用名称的应用
    const targetApp = apps.find((app: any) => app.name === appName)
    if (!targetApp) {
      return {
        success: false,
        message: `在分类 "${category}/${subCategory}" 下未找到应用名为 "${appName}" 的应用`,
        data: null,
        error: 'APP_NOT_FOUND',
        category,
        subCategory,
        appName,
        totalAppsInCategory: apps.length
      }
    }
    
    // 获取请求域名并替换图片域名
    const hostname = event.node.req.headers.host || ''
    const processedApp = replaceImageDomains(targetApp, hostname)
    
    // 返回成功结果
    return {
      success: true,
      message: '获取应用信息成功',
      data: processedApp,
      category,
      subCategory,
      appName,
      totalAppsInCategory: apps.length
    }
    
  } catch (error: any) {
    console.error('获取应用信息错误:', error)
    return {
      success: false,
      message: '获取应用信息过程中发生错误',
      data: null,
      error: process.env.NODE_ENV === 'development' ? error?.message : 'INTERNAL_ERROR'
    }
  }
})
